package com.hjl.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * BaseServlet为了解决servlet和web.xml冗余问题
 *
 * @author Lenovo
 * @version 1.0
 * @date 2021/10/8 11:25
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //完成方法分发
        //获取请求路径
        String uri = req.getRequestURI();
        // 如 /user/findUserByPage
        System.out.println(uri);
        //获取方法名称
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        System.out.println(methodName);
        //反射
        try {
            //获得方法名（通过对象名this .getClass()获取）   getDeclaredMethod忽略修饰符
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //暴力反射  private修饰时使用 method.setAccessible(true)
            //执行方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 简化重复的json操作，使用Jackson （方法重载）
     * 直接将传入的对象序列化为json，并写回客户端
     *
     * @param object 对象
     * @author Lenovo
     * @date 2021/10/8 21:18
     */
    public void writeValue(Object object, HttpServletResponse response) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(), object);
    }

    /**
     * 将传入的对象序列化为json，返回
     */
    public String writeValue(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
}
